<template>
	<view class="container">
		<view class="header">
			<view class="header-main">
				<view class="title">受邀采购单</view>
				<button class="refresh-btn" @click="onRefresh" :disabled="loading">{{ loading ? '刷新中...' : '刷新' }}</button>
			</view>
			<view class="subtitle">您被邀请参与的采购项目</view>
		</view>
		
		<view class="search-box">
			<input class="search-input" type="text" v-model="query" placeholder="搜索采购单..." @confirm="search" />
			<button class="search-btn" @click="search">搜索</button>
		</view>
		
		<view class="list-container">
			<view class="list-item" v-for="(item, index) in auctionList" :key="index" @click="goToDetail(item._id)">
				<view class="item-header">
					<text class="item-title">{{ item.title }}</text>
					<text class="item-status" :class="item.status">{{ statusText(item.status) }}</text>
				</view>
				<view class="item-content">
					<text class="item-number">编号: {{ item.serial_number }}</text>
					<text class="item-price">起始价: ¥{{ item.start_price }}</text>
					<text class="item-time">截止: {{ formatDate(item.end_time) }}</text>
				</view>
				<view class="item-footer">
					<button class="action-btn bid-btn" @click.stop="goToBidding(item._id)">去报价</button>
					<button class="action-btn detail-btn" @click.stop="goToDetail(item._id)">详情</button>
				</view>
			</view>
			
			<view class="no-data" v-if="!loading && auctionList.length === 0">
				<text>暂无受邀采购单</text>
			</view>
			
			<view class="loading" v-if="loading && auctionList.length === 0">
				<text>加载中...</text>
			</view>
		</view>
	</view>
</template>

<script>
	const pageSize = 10;
	const db = uniCloud.database();

	export default {
		data() {
			return {
				query: '',
				auctionList: [],
				loading: false,
				pagination: {
					page: 1,
					pageSize: pageSize,
					total: 0
				},
				userId: null
			}
		},
		onLoad() {
			// 页面加载时获取当前用户信息
			this.setCurrentUser();
		},
		onShow() {
			// 页面显示时刷新数据
			if (this.userId) {
				this.loadData(true);
			}
		},
		onReachBottom() {
			// 页面触底时加载下一页
			this.loadData();
		},
		methods: {
			onRefresh() {
				this.loadData(true);
			},
			            setCurrentUser() {
				const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
				if (userInfo._id) {
					this.userId = userInfo._id;
				} else {
					uni.showToast({
						title: '获取用户信息失败，请重新登录',
						icon: 'none'
					});
				}
			},
			async loadData(isReset = false) {
				if (isReset) {
					this.pagination.page = 1;
					this.auctionList = [];
					this.pagination.total = 0;
				}

				// 检查是否正在加载或已无更多数据
				if (this.loading || (this.auctionList.length >= this.pagination.total && this.pagination.total > 0 && !isReset)) {
					return;
				}
				
				if (!this.userId) {
					uni.showToast({ title: '未登录，无法加载数据', icon: 'none' });
					return;
				}

				this.loading = true;

				try {
					// 基础查询条件：当前用户必须在受邀列表中
					let whereClause = `'${this.userId}' in invited_supplier_ids`;

					// 如果有搜索查询
					const searchQuery = this.query.trim();
					if (searchQuery) {
						// 模糊查询标题
						whereClause += ` && new RegExp('${searchQuery}', 'i').test(title)`;
					}

					const queryRes = await db.collection('auctions')
						.where(whereClause)
						.orderBy('create_time', 'desc')
						.skip((this.pagination.page - 1) * this.pagination.pageSize)
						.limit(this.pagination.pageSize)
						.get({
							getCount: true
						});

					if (queryRes.result && queryRes.result.data) {
						const {
							data,
							count
						} = queryRes.result;
						if (isReset) {
							this.auctionList = data;
						} else {
							this.auctionList.push(...data);
						}
						this.pagination.total = count;
						if (data.length > 0) {
							this.pagination.page++;
						}
					} else {
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
					console.error(err);
				} finally {
					this.loading = false;
				}
			},

			search() {
				this.loadData(true);
			},

			formatDate(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			},

			statusText(status) {
				const statusMap = {
					'bidding': '竞价中',
					'finished': '已结束'
				};
				return statusMap[status] || status;
			},

			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/auctions/detail?id=${id}`
				});
			},

			goToBidding(auctionId) {
				uni.navigateTo({
					url: `/pages/bids/add?auctionId=${auctionId}`
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
	}
	
	.header {
		margin-bottom: 30rpx;
	}

	.header-main {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.refresh-btn {
		padding: 0 25rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 26rpx;
		background-color: #007AFF;
		color: white;
		border-radius: 8rpx;
		margin: 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.refresh-btn[disabled] {
		background-color: #a0cfff;
	}
	
	.subtitle {
		font-size: 28rpx;
		color: #999;
		margin-top: 10rpx;
	}
	
	.search-box {
		display: flex;
		margin-bottom: 30rpx;
	}
	
	.search-input {
		flex: 1;
		padding: 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 10rpx;
	}
	
	.search-btn {
		margin-left: 20rpx;
		padding: 20rpx;
		background-color: #007AFF;
		color: white;
		border-radius: 10rpx;
	}
	
	.list-container {
		background-color: white;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.list-item {
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.list-item:last-child {
		border-bottom: none;
	}
	
	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.item-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
	}
	
	.item-status {
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 5rpx;
	}
	
	.item-status.bidding {
		background-color: #e6fffb;
		color: #007AFF;
	}
	
	.item-status.finished {
		background-color: #f0f0f0;
		color: #999;
	}
	
	.item-content {
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
	}
	
	.item-content text {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	
	.item-footer {
		display: flex;
		justify-content: flex-end;
	}
	
	.action-btn {
		padding: 15rpx 30rpx;
		font-size: 26rpx;
		border-radius: 8rpx;
		margin-left: 20rpx;
	}
	
	.bid-btn {
		background-color: #007AFF;
		color: white;
	}
	
	.detail-btn {
		background-color: #f0f0f0;
		color: #333;
	}
	
	.no-data, .loading {
		text-align: center;
		padding: 50rpx;
		color: #999;
	}
</style>